﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;

public class Marquee : MonoBehaviour {

	// 用来定位左右边界
	public RectTransform leftEdgetRectTransform;
	public RectTransform rightEdgeRectTransform;

	public float speed = 100;

	private RectTransform rectTransform;
	private bool moving = false;

	private Queue<string> stringQueue = new Queue<string>();

    private void Awake()
    {
		rectTransform = GetComponent<RectTransform>();
    }

    public void AddText(string text)
    {
		stringQueue.Enqueue(text);
    }

	void Run () {
		if (stringQueue.Count == 0) return;

		string text = stringQueue.Dequeue();
		
		if (text != null)
        {
			Transform transform = gameObject.transform.Find("Text");
			Text textComp;
			if (transform == null)
            {
				GameObject go = new GameObject();
				go.name = "Text";
				textComp = go.AddComponent<Text>();
				go.transform.SetParent(gameObject.transform, false);
            }
			else
            {
				textComp = transform.GetComponent<Text>();
            }


			// 测算结束位置 (无论什么样形式的锚点）
			RectTransform rectTransform = transform.GetComponent<RectTransform>();
			rectTransform.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Left, -textComp.preferredWidth, textComp.preferredWidth);
			float endValue = rectTransform.offsetMin.x;

			// 初始化内容和位置 (无论什么样形式的锚点）
			textComp.text = text;
			textComp.horizontalOverflow = HorizontalWrapMode.Overflow;			
			rectTransform.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Right, -textComp.preferredWidth, textComp.preferredWidth);
			float startValue = rectTransform.offsetMin.x;

			// 移动		
			float totalDistance = Mathf.Abs(endValue - startValue);
			float duration = totalDistance / speed;

			Tweener tweener = rectTransform.DOAnchorPosX(leftEdgetRectTransform.anchoredPosition.x, duration).SetEase(Ease.Linear);
			moving = true;
            tweener.OnComplete(() =>
            {
				moving = false;
            });

        }
	}

    private void Update()
    {
        // for fast test. 如果是在实际使用中，只要在外部得到数据后，通过AddText()接口送入数据即可。
        //if (Input.GetKeyDown(KeyCode.A))
        //{
        //    AddText("hello, marquee!" + Random.Range(1, 1000));
        //}

        if (!moving)
        {
			Run();
        }
    }
}